package com.xiechuang.helper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;

import static java.net.URLEncoder.encode;

/**
 * @Description: cookie助手
 * @Author: xiechuang
 * @Date: 2023/1/11
 */
public class CookieHelper {

    private final static Logger logger = LoggerFactory.getLogger(CookieHelper.class);

    /**
     * 获取Cookie 信息
     *
     * @param
     * @return
     */
    public static Map getCookies(HttpServletRequest request) {
        Map input = new LinkedHashMap();
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                try {
                    input.put(cookie.getName(), URLDecoder.decode(cookie.getValue(), "UTF-8"));
                } catch (Exception ex) {
                    logger.error(ex.getMessage() + "：", ex);
                }
            }
        }
        return input;
    }

    public static Map getCookies() {
        return getCookies(RequestHelper.getRequest());
    }

    /**
     * 设置Cookie 信息
     *
     * @param
     * @return
     */
    public static void setCookies(HttpServletResponse response, String name, String value, String path, int magAge) {
        Cookie cookie = null;
        try {
            cookie = new Cookie(name, encode(value, "utf-8"));
            cookie.setMaxAge(magAge);
            cookie.setPath(path);
            response.addCookie(cookie);
        } catch (Exception ex) {
            logger.error(ex.getMessage() + "：", ex);
        }
    }

    /**
     * 清除 Cookies
     */
    public static void clearCookies() {
        HttpServletRequest request = RequestHelper.getRequest();
        HttpServletResponse response = RequestHelper.getResponse();
        //清除 Cookies
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            cookie.setMaxAge(-1);
            response.addCookie(cookie);
        }
    }

    /**
     * 获取 Cookie
     */
    public static Cookie getCookieByName(String name, HttpServletRequest request) {
        Cookie cookies[] = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (name.equals(cookie.getName())) {
                    return cookie;
                }
            }
        }
        return null;
    }

    /**
     * 删除cookie
     */
    public static void removeCookieByName(String name, HttpServletRequest request, HttpServletResponse response) {
        Cookie cookie = getCookieByName(name, request);
        if (cookie != null) {
            //设置过期时间为立即。
            cookie.setMaxAge(0);
            response.addCookie(cookie);
        }
    }

    public static void writeCookie(String name, String value, HttpServletResponse response) {
        //使用URL进行编码，避免写入cookie错误。
        try {
            response.addCookie(new Cookie(name, URLEncoder.encode(value, "UTF-8")));
        } catch (Exception ex) {
            logger.error("Encode with URL error", ex);
        }
    }

}
